﻿<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="1300" destroy-on-close :close-on-click-modal="false"
        :before-close="handleBeforeClose">
        <el-form :model="entityObj" :rules="rules" :disabled="mode == 'Show'" ref="dialogForm" label-width="100px">
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="入库时间" prop="inStockDate">
                        <el-date-picker v-model="entityObj.inStockDate" :default-time="defaultTime" type="datetime"
                            value-format="YYYY-MM-DD" format="YYYY-MM-DD" placeholder="请输入要货时间" style="width: 100%" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="入库仓库" prop="warehouses">
                        <sc-warehouse-select ref="orgselect" :props="warehouseProps" :selectKeyValue="'warehouseId'"
                            v-model="entityObj.warehouses" :multiple="false" style="width: 100%"
                            @fatherMethod="warehouseMethod">
                        </sc-warehouse-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="入库类型" prop="inStockType">
                        <el-select placeholder="---请选择状态---" v-model="entityObj.inStockType" style="width: 100%">
                            <el-option label="---请选择---" value />
                            <el-option v-for="item in warehouseInStockType" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item prop="supplierName" label-width="120px" label="供应商">
                        <!-- <sc-auto-complete :orgType="orgType == 1 ? 3 : 0"
                            :queryType="orgType == 1 ? 'supplier/pages' : 'supplier/store-org-list'"
                            :placeholder="'---请输入申请单位---'" v-model="entityObj.supplierName"
                            @handleSelect="(e) => { this.entityObj.supplierName = e.supplierName, this.entityObj.supplierId = e.supplierId, this.entityObj.supplierType = e.orgType ?? 3 }"
                            style="width: 100%" /> --> 
                        <!-- <sc-supplier-select ref="orgselect"
                            :queryType="orgType == 1 ? 'supplier/pages' : 'supplier/store-org-pages'"
                            :props="supplierProps" :selectKeyValue="'supplierId'" v-model="entityObj.suppliers"
                            :multiple="false" style="width: 100%">
                        </sc-supplier-select> -->

                        <sc-supplier-select-input ref="orgselect"
                            :queryType="orgType == 1 ? 'supplier/pages' : 'supplier/store-org-pages'"
                            :props="supplierProps" :selectKeyValue="'supplierId'" v-model="entityObj.suppliers"
                            :multiple="false" style="width: 100%">
                        </sc-supplier-select-input>
                        
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="创建人" prop="crName">
                        <el-input v-model="entityObj.crName" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="创建时间" prop="crDate">
                        <el-date-picker v-model="entityObj.crDate" :default-time="defaultTime" type="datetime"
                            value-format="YYYY-MM-DD" format="YYYY-MM-DD" placeholder="请输入创建时间" style="width: 100%" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="创建类型" prop="createType">
                        <el-select placeholder="---请选择创建类型---" v-model="entityObj.createType" style="width: 100%">
                            <el-option label="---请选择---" value />
                            <el-option v-for="item in optionsCreateType" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="来源" prop="sourceType">
                        <el-select placeholder="---请选择来源---" v-model="entityObj.sourceType" style="width: 100%">
                            <el-option label="---请选择---" value />
                            <el-option v-for="item in optionsSourceType" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="备注">
                        <el-input v-model="entityObj.remarks" type="textarea" :rows="2" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="入库信息" prop="inStockItems">
                        <el-button size="small" @click="addMaterial()">新增物料</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px">
                        <el-table :data="entityObj.inStockItems" border style="width: 100%" show-summary>
                            <el-table-column label="物料编码" width="100">
                                <template #default="scope">{{ scope.row.materialCode }}</template>
                            </el-table-column>
                            <el-table-column label="物料名称" width="130">

                                <template #default="scope">{{ scope.row.materialName }}</template>
                            </el-table-column>
                            <el-table-column label="规格" width="120">

                                <template #default="scope">{{ scope.row.materialSpecs }}</template>
                            </el-table-column>
                            <el-table-column label="物料类别" width="120">

                                <template #default="scope">{{ scope.row.materialTypeName }}</template>
                            </el-table-column>
                            <el-table-column label="单位" width="80">

                                <template #default="scope">{{ scope.row.unitName }}</template>
                            </el-table-column>
                            <el-table-column label="入库数量" prop="qty">

                                <template #default="scope">
                                    <el-input-number v-model="scope.row.qty" style="width: 100%" :step="1"
                                        controls-position="right"></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="入库单价" prop="price">

                                <template #default="scope">
                                    <el-input-number v-model="scope.row.price" style="width: 100%" :step="0.01"
                                        controls-position="right"></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="金额" width="90" prop="totalAmount">

                                <template #default="scope">{{ scope.row.totalAmount=scope.row.qty * scope.row.price
                                    }}</template>
                            </el-table-column>
                            <el-table-column label="备注">

                                <template #default="scope">
                                    <el-input v-model="scope.row.remarks" style="width: 100%" />
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="80">

                                <template #default="scope">
                                    <el-button size="small" @click="deleteRow(scope.$index, scope.row)">移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <el-button @click="handleBeforeClose">取 消</el-button>
            <el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit(1)">暂 存</el-button>
            <el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit(2)">保 存</el-button>
        </template>

        <template>
            <el-dialog v-model="materialState" title="选择商品" :width="1300" :center="true" append-to-body
                style="height: 480px">
                <el-row>
                    <sc-material-choice ref="scMaterialChoice" :queryType="'material/item-pages'"></sc-material-choice>
                </el-row>
                <template #footer>
                    <el-button @click="materialState = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setMaterialChoice">确定</el-button>
                </template>
            </el-dialog>
        </template>
    </el-dialog>
</template>



<script>
import tool from "@/utils/tool";
export default {
    emits: ["success", "closed"],
    data() {
        return {
            mode: "Add",
            titleMap: {
                Add: "新增",
                Edit: "编辑",
                Show: "查看",
            },
            entityObj: {
                inStockItems: [],
            },
            materialState: false,
            storeState: false,
            queryList: {},
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            //验证规则
            rules: {
                inStockDate: [
                    { required: true, type: "string", message: "请填写" },
                ],
                warehouses: [
                    { required: true, type: "object", message: "请填写" },
                ],
                inStockType: [
                    { required: true, type: "number", message: "请填写" },
                ],
                crName: [{ required: true, type: "string", message: "请填写" }],
                crDate: [{ required: true, type: "string", message: "请填写" }],
                createType: [
                    { required: true, type: "number", message: "请填写" },
                ],
                sourceType: [
                    { required: true, type: "number", message: "请填写" },
                ],
                inStockItems: [
                    {
                        required: true,
                        type: "array",
                        message: "请填写",
                        trigger: "change",
                    },
                ],
                // suppliers: [
                //     {
                //         required: true,
                //         type: "object",
                //         message: "请选择供应商",
                //         trigger: "change",
                //     },
                // ],
            },
            supplierProps: {
                label: "supplierName",
                value: "supplierId",
            },
            warehouseProps: {
                label: "warehouseName",
                value: "warehouseId",
            },
            materialProps: {
                label: "materialCode",
                value: "materialId",
                items: "materialItems",
            },
            optionsCreateType: [],
            optionsSourceType: [],
            optionsInStockType: [],
            warehouseInStockType: [],
            itemsData: [],
            orgType: 1,
        };
    },
    computed: {},
    methods: {
        //显示=
        async open(mode = "Add") {
            this.mode = mode;
            this.visible = true;

            return this;
        },
        handleBeforeClose() {
            this.$confirm("信息未保存,确定要关闭吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.visible = false;
                })
                .catch(() => {
                    // 用户点击了取消按钮，不执行关闭
                });
        },
        //表单提交方法
        submit(status) {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    this.isSaveing = true;
                    try {
                        if (this.entityObj.suppliers && this.entityObj.suppliers.supplierId) {
                            this.entityObj.supplierId = this.entityObj.suppliers.supplierId;
                            this.entityObj.supplierName = this.entityObj.suppliers.supplierName;
                        } else if (this.entityObj.suppliers) {
                            this.entityObj.supplierId = 0 
                            this.entityObj.supplierName = this.entityObj.suppliers // supplierName;
                        }
                        this.entityObj.warehouseId = this.entityObj.warehouses.warehouseId;

                        // console.log("提交2", this.entityObj);
                        // return
                        var returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                this.mode == "Add"
                                    ? "in-stock/create"
                                    : "in-stock/update",
                                { ...this.entityObj, auditStatus: status }
                            );
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$emit("fatherMethod");
                            this.isSaveing = false;
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                        }
                    } catch (error) {
                        this.loading = false;
                        this.isSaveing = false;
                        return false;
                    }
                }
            });
        },
        //表单注入数据
        async setData(id) {
            if (id && id > 0) {
                try {
                    var returnValue = await this.$API.auth.GetProcessApi.get(
                        "in-stock/detail/" + id,
                        {}
                    );
                    
                    if (returnValue.status == 200) {
                        this.entityObj = returnValue.response;
                        this.entityObj.suppliers = {
                            supplierId: this.entityObj.supplierId,
                            supplierName: this.entityObj.supplierName,
                        };
                        this.entityObj.warehouses = {
                            warehouseId: this.entityObj.warehouseId,
                            warehouseName: this.entityObj.warehouseName,
                            isExternal: this.entityObj.isExternal,
                        };
                        this.warehouseMethod(this.entityObj.warehouses);
                    } else {
                        this.$message.error("操作失败:" + returnValue.msg);
                    }
                } catch (error) {
                    this.loading = false;
                    return false;
                }
            }
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "base-dictionary/options",
                    { Codes: ["InStockType", "CreateType", "SourceType"] }
                );
                if (returnValue.status == 200) {
                    this.optionsCreateType = returnValue.response.find(
                        (p) => p.code == "CreateType"
                    ).optionsDetails;
                    this.optionsSourceType = returnValue.response.find(
                        (p) => p.code == "SourceType"
                    ).optionsDetails;
                    this.optionsInStockType = returnValue.response.find(
                        (p) => p.code == "InStockType"
                    ).optionsDetails;
                    this.warehouseInStockType = this.optionsInStockType;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        addMaterial() {
            this.materialState = true;
        },
        deleteRow(index) {
            this.entityObj.inStockItems.splice(index, 1);
        },
        setMaterialChoice() {
            console.log(this.entityObj.inStockItems);
            let materials = this.$refs.scMaterialChoice.selectionRows;
            materials.map((p) => {
                debugger;
                this.entityObj.inStockItems.push({
                    materialId: p.materialId,
                    materialCode: p.materialCode,
                    materialName: p.materialName,
                    materialSpecs: p.materialSpecs,
                    materialTypeId: p.materialTypeId,
                    materialTypeName: p.materialTypeName,
                    unitName: p.unitName,
                    qty: 0,
                    price: 0,
                    totalAmount: 0,
                    remarks: "",
                    materialItemId: p.materialItemId,
                });
            });
            this.materialState = false;
        },
        purchaseUnityChange(value) {
            this.entityObj.purchaseRealName = this.optionsPurchaseUnity.find(
                (p) => p.purchaseUnityId == value
            ).realName;
            this.entityObj.purchaseMobile = this.optionsPurchaseUnity.find(
                (p) => p.purchaseUnityId == value
            ).mobile;
        },
        warehouseMethod(warehouse) {
            //当仓库为托管仓时默认为赠送入库
            if (
                warehouse &&
                warehouse.isExternal &&
                warehouse.warehouseType == 1
            ) {
                this.warehouseInStockType = this.optionsInStockType.filter(
                    (p) => p.value == 5
                );
                this.entityObj.inStockType = 5;
            } else if (
                warehouse &&
                warehouse.isExternal &&
                warehouse.warehouseType == 2
            ) {
                this.warehouseInStockType = this.optionsInStockType.filter(
                    (p) => p.value == 9
                );
                this.entityObj.inStockType = 9;
            } else {
                this.warehouseInStockType = this.optionsInStockType;
            }
        },
    },
    async mounted() {
        this.entityObj.inStockDate = tool.formatDate(new Date(), 1);
        this.entityObj.crName = tool.data.get("USER_INFO").Name;
        this.orgType = tool.data.get("USER_INFO").AccountType;
        this.entityObj.crDate = tool.formatDate(new Date());
        await this.initOptions();
    },
};
</script>

<style></style>
